from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.orm import Session
from typing import List, Optional
from datetime import datetime
from backend.database import SessionLocal
from backend.models import Message, User
from backend.schemas import MessageCreate, MessageResponse
from sqlalchemy import or_, and_
import logging

# 日志配置
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

router = APIRouter(prefix="")

def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()

# 获取用户消息列表
@router.get("/api/messages", response_model=List[MessageResponse])
async def get_messages(
    user_id: int = Query(..., description="用户ID"),
    db: Session = Depends(get_db)
):
    """
    获取指定用户发送和接收的所有消息列表，按发送时间降序
    """
    msgs = db.query(Message).filter(
        or_(
            Message.sender_id == user_id,
            Message.receiver_id == user_id
        )
    ).order_by(Message.send_time.desc()).all()
    return msgs

# 创建消息
@router.post("/api/messages", response_model=MessageResponse)
async def create_message(
    message: MessageCreate,
    sender_id: int = Query(..., description="发送者用户ID"),
    receiver_id: int = Query(..., description="接收者用户ID"),
    db: Session = Depends(get_db)
):
    """
    创建新消息，需要指定发送者ID和接收者ID
    """
    # 验证发送者和接收者
    sender = db.query(User).filter(User.user_id == sender_id).first()
    if not sender:
        raise HTTPException(status_code=404, detail="发送者不存在")
    receiver = db.query(User).filter(User.user_id == receiver_id).first()
    if not receiver:
        raise HTTPException(status_code=404, detail="接收者不存在")

    db_msg = Message(
        sender_id=sender_id,
        receiver_id=receiver_id,
        related_job_id=message.related_job_id,
        content=message.content,
        send_time=datetime.utcnow()
    )
    db.add(db_msg)
    db.commit()
    db.refresh(db_msg)
    logger.info(f"消息已创建: message_id={db_msg.message_id}")
    return db_msg

# 获取两个用户之间的会话消息
@router.get("/api/conversations", response_model=List[MessageResponse])
async def get_conversation(
    user1: int = Query(..., description="用户1的ID"),
    user2: int = Query(..., description="用户2的ID"),
    db: Session = Depends(get_db)
):
    """
    获取两个用户之间的会话消息，按发送时间升序
    """
    msgs = db.query(Message).filter(
        or_(
            and_(Message.sender_id == user1, Message.receiver_id == user2),
            and_(Message.sender_id == user2, Message.receiver_id == user1)
        )
    ).order_by(Message.send_time.asc()).all()
    return msgs

# 更新消息已读状态
@router.put("/api/messages/{message_id}/read")
async def mark_message_as_read(
    message_id: int,
    db: Session = Depends(get_db)
):
    """
    将消息标记为已读
    """
    message = db.query(Message).filter(Message.message_id == message_id).first()
    if not message:
        raise HTTPException(status_code=404, detail="消息不存在")
    
    message.is_read = True
    db.commit()
    return {"status": "success"}

# 获取用户信息
@router.get("/api/users/{user_id}")
async def get_user_info(
    user_id: int,
    db: Session = Depends(get_db)
):
    """
    获取指定用户的信息
    """
    user = db.query(User).filter(User.user_id == user_id).first()
    if not user:
        raise HTTPException(status_code=404, detail="用户不存在")
    return {
        "user_id": user.user_id,
        "username": user.username,
        "email": user.email
    } 